<template>
  <div>
    <!-- views/Register.vue -->
    <mt-header title="登录">
      <mt-button icon="back" slot="left"></mt-button>
      <router-link to="/register" slot="right">注册</router-link>
    </mt-header>

    <mt-field type="text" label="用户名"
      v-model="name" :state="nameState"
      placeholder="请输入用户名"></mt-field>
    <mt-field type="password" label="密码"
      v-model="pwd" :state="pwdState"
      placeholder="请输入密码"></mt-field>

    <mt-button @click="checkForm" type="primary" size="large">
      安全登录
    </mt-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: '',       // 绑定用户名输入框的值
      nameState: '',  // 绑定用户名的状态属性
      pwd: '',       
      pwdState: '',  
    }
  },

  methods: {
    /** 验证表单 */
    checkForm(){
      if(this.checkName() && this.checkPwd()){
        console.log('表单验证通过，执行登录...')
        let params = `username=${this.name}&password=${this.pwd}`                      
        this.axios.post('/login', params).then(res=>{
          console.log('登录结果', res)
          if(res.data.code==200){ // 登录成功
            this.$toast({
              message: '登录成功',
              position: 'bottom',
              duration: 2000
            })
            // 登录成功，更新vuex
            this.$store.commit('loginOK', this.name)

            this.$router.push('/home/index')
          }else {  // 登录失败
            this.$messagebox('提示', '账号密码输入错误，请重试')                              
          }
        })
      }
    },

    checkPwd(){  /** 验证密码 */
      let reg = /^\d{6}$/
      if(reg.test(this.pwd)){ // 验证成功
        this.pwdState = 'success'
        return true
      }else{ // 验证失败
        this.pwdState = 'error'
        return false
      }
    },

    checkName(){  /** 验证账号 */
      let reg = /^\w{6,15}$/
      if(reg.test(this.name)){ // 验证成功
        this.nameState = 'success'
        return true
      }else{ // 验证失败
        this.nameState = 'error'
        return false
      }
    }

  },
}
</script>




